package org.eiahe.hr.attendance.listener;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eiahe.hr.attendance.event.AnnualLeaveDeductEvent;
import org.eiahe.hr.attendance.service.IAnnualLeaveService;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 年假事件监听器
 *
 * @author zhangnn
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AnnualLeaveEventListener {

    private final IAnnualLeaveService annualLeaveService;

    /**
     * 处理年假扣减事件
     * 当年假类型的请假申请通过后，自动扣减年假天数
     */
    @Async
    @EventListener
    public void handleAnnualLeaveDeduct(AnnualLeaveDeductEvent event) {
        log.info("处理年假扣减事件 - 工号: {}, 年份: {}, 扣减天数: {}, 请假单号: {}",
                event.getEmployeeNo(), event.getYear(), event.getDays(), event.getLeaveNo());

        try {
            // 扣减年假天数
            annualLeaveService.deductAnnualLeave(
                    event.getEmployeeNo(),
                    event.getYear(),
                    event.getDays());

            log.info("年假扣减成功 - 工号: {}, 年份: {}, 扣减天数: {}",
                    event.getEmployeeNo(), event.getYear(), event.getDays());

        } catch (Exception e) {
            log.error("年假扣减失败 - 工号: {}, 请假单号: {}",
                    event.getEmployeeNo(), event.getLeaveNo(), e);
            // 注意：这里如果扣减失败，需要考虑是否要回滚请假审批
            // 或者通过其他机制通知管理员处理
        }
    }
}
